package com.senlingspace.system.service.impl;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import com.senlingspace.common.core.domain.entity.SysDept;
import com.senlingspace.common.exception.UtilException;
import com.senlingspace.common.utils.DateUtils;
import com.senlingspace.common.utils.PageUtils;
import com.senlingspace.common.utils.SecurityUtils;
import com.senlingspace.system.domain.SlkjShop;
import com.senlingspace.system.domain.SlkjStoreCost;
import com.senlingspace.system.domain.SlkjStoreCostMarketing;
import com.senlingspace.system.domain.dto.MarketingDto;
import com.senlingspace.system.domain.dto.StoreCostDto;
import com.senlingspace.system.domain.vo.SlkjShopVo;
import com.senlingspace.system.domain.vo.SlkjTicketCategoryVo;
import com.senlingspace.system.mapper.SlkjShopMapper;
import com.senlingspace.system.mapper.SlkjStoreCostMapper;
import com.senlingspace.system.mapper.SlkjStoreCostMarketingMapper;
import com.senlingspace.system.mapper.SysDeptMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.senlingspace.system.service.ISlkjStoreCostService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 门店成本上报Service业务层处理
 *
 * @author SenlingSpace
 * @date 2024-07-22
 */
@Service
@Slf4j
public class SlkjStoreCostServiceImpl implements ISlkjStoreCostService
{
    @Autowired
    private SlkjStoreCostMapper slkjStoreCostMapper;

    @Autowired
    private SlkjStoreCostMarketingMapper slkjStoreCostMarketingMapper;
    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SlkjShopMapper slkjShopMapper;

    /**
     * 查询门店成本上报
     * a
     * @param storeId 门店成本上报主键
     * @return 门店成本上报
     */
    @Override
    public SlkjStoreCost selectSlkjStoreCostByStoreId(Long storeId)
    {
       return slkjStoreCostMapper.selectSlkjStoreCostByStoreId(storeId);
    }


    /**
     *
     *  返回详情
     * @author Administrator
     * @param storeId 报表逐渐id
     * @return com.senlingspace.system.domain.dto.StoreCostDto
     */
    @Override
    public StoreCostDto selectStoreCostTdoByStoreId(Long storeId) {
        StoreCostDto storeCostDto = new StoreCostDto();
        SlkjStoreCost slkjStoreCost = slkjStoreCostMapper.selectSlkjStoreCostByStoreId(storeId);
        List<MarketingDto> marketingList = slkjStoreCostMarketingMapper.selectSlkjStoreCostMarketingLists(slkjStoreCost.getStoreId());
        storeCostDto.setStoreId(slkjStoreCost.getStoreId());
        storeCostDto.setMarketingList(marketingList);
        storeCostDto.setShopId(slkjStoreCost.getShopId());
        storeCostDto.setStoreMonth(slkjStoreCost.getStoreMonth());
        storeCostDto.setVenueRent(String.valueOf(slkjStoreCost.getVenueRent()));
        storeCostDto.setProcurement(String.valueOf(slkjStoreCost.getProcurement()));
        storeCostDto.setPurchaseInstructions(slkjStoreCost.getPurchaseInstructions());
        storeCostDto.setEquipmentMaintenance(String.valueOf(slkjStoreCost.getEquipmentMaintenance()));
        storeCostDto.setMaintenanceInstructions(slkjStoreCost.getMaintenanceInstructions());
        storeCostDto.setEmployees(slkjStoreCost.getEmployees());
        storeCostDto.setPersonnelCosts(String.valueOf(slkjStoreCost.getPersonnelCosts()));
        storeCostDto.setMarketingCost(String.valueOf(slkjStoreCost.getMarketingCost()));
        storeCostDto.setDeplete(String.valueOf(slkjStoreCost.getDeplete()));
        storeCostDto.setTotalCost(String.valueOf(slkjStoreCost.getTotalCost()));
        return  storeCostDto;
    }

    /**
     * 查询门店成本上报列表
     *
     * @param slkjStoreCost 门店成本上报
     * @return 门店成本上报
     */
    @Override
    public PageInfo<SlkjStoreCost> selectSlkjStoreCostList(SlkjStoreCost slkjStoreCost, Long deptId, boolean pageFlag) {
        if (deptId == null){
            deptId = SecurityUtils.getDeptId();
        }
        List<SlkjShop> slkjShops = slkjShopMapper.selectSlkjShopByDeptIdLists(deptId);
        List<Long> shopIds = new ArrayList<>();
        shopIds = slkjShops.stream()
                .map(SlkjShop::getShopId)
                .collect(Collectors.toList());
        Page<Object> page = PageUtils.startPageExt(pageFlag);
        // 查询所有成本记录
        List<SlkjStoreCost> slkjStoreCosts = slkjStoreCostMapper.selectSlkjStoreCostByShopIds(shopIds);
        long total = page.getTotal();
        PageInfo<SlkjStoreCost> pageInfo = new PageInfo<>(slkjStoreCosts);
        pageInfo.setTotal(total);
        pageInfo.setPageNum(page.getPageNum());
        pageInfo.setPageSize(page.getPageSize());
        return pageInfo;
    }

    /**
     * 新增门店成本上报
     *
     * @param costDto 门店成本上报
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertSlkjStoreCost(StoreCostDto costDto)
    {
        String storeMonth = costDto.getStoreMonth();
        Long shopId = costDto.getShopId();
        //根据门店id和月份查询门店这个月是否提交过成本表
        ArrayList<SlkjStoreCost> slkjStoreCosts = slkjStoreCostMapper.selectSlkjStoreCostByShopId(shopId,storeMonth);
        if(!slkjStoreCosts.isEmpty()){
            throw new IllegalArgumentException("门店成本上报已存在");
        }
        /**
         * 计算前段传值
         */
        Long venueRent = new BigDecimal(costDto.getVenueRent()).multiply(BigDecimal.valueOf(100)).longValue();
        Long procurement = new BigDecimal(costDto.getProcurement()).multiply(BigDecimal.valueOf(100)).longValue();
        Long equipmentMaintenance = new BigDecimal(costDto.getEquipmentMaintenance()).multiply(BigDecimal.valueOf(100)).longValue();
        Long personnelCosts = new BigDecimal(costDto.getPersonnelCosts()).multiply(BigDecimal.valueOf(100)).longValue();
        Long deplete = new BigDecimal(costDto.getDeplete()).multiply(BigDecimal.valueOf(100)).longValue();
        Long marketingCosts = new BigDecimal(costDto.getMarketingCost()).multiply(BigDecimal.valueOf(100)).longValue();

        Long num = venueRent + procurement + equipmentMaintenance + personnelCosts + deplete + marketingCosts;
        BigDecimal totalCost = new BigDecimal(costDto.getTotalCost());
        long calculatedNum = totalCost.multiply(BigDecimal.valueOf(100)).longValue();

        if (!num.equals(Long.valueOf(calculatedNum))) {
            throw new UtilException("成本合计与计算结果不一致");
        }
        //会有多个营销成本明细   这是list<dto>
        //循环获取营销成本
        List<MarketingDto> marketingList = costDto.getMarketingList();
        SlkjStoreCostMarketing slkjStoreCostMarketing = new SlkjStoreCostMarketing();
        SlkjStoreCost slkjStoreCost = new SlkjStoreCost();
        slkjStoreCost.setShopId(costDto.getShopId());
        slkjStoreCost.setShopName(costDto.getShopName());
        slkjStoreCost.setStoreMonth(storeMonth);
        slkjStoreCost.setVenueRent(venueRent);
        slkjStoreCost.setProcurement(procurement);
        slkjStoreCost.setPurchaseInstructions(costDto.getPurchaseInstructions());
        slkjStoreCost.setEquipmentMaintenance(equipmentMaintenance);
        slkjStoreCost.setMaintenanceInstructions(costDto.getMaintenanceInstructions());
        slkjStoreCost.setEmployees(costDto.getEmployees());
        slkjStoreCost.setPersonnelCosts(personnelCosts);
        slkjStoreCost.setDeplete(deplete);
        slkjStoreCost.setMarketingCost(marketingCosts);
        slkjStoreCost.setTotalCost(num);
        slkjStoreCost.setCreateBy(SecurityUtils.getUsername());
        slkjStoreCost.setCreateTime(DateUtils.getNowDate());
        slkjStoreCost.setDelFlag("0");
        int storeCostNum = slkjStoreCostMapper.insertSlkjStoreCost(slkjStoreCost);
        Long storeId = slkjStoreCost.getStoreId();
        if (marketingList != null) {
            Long marketingCost = 0L;
            for(MarketingDto  marketing : marketingList){
                //循环向子表插入数据
                BigDecimal costs = new BigDecimal(marketing.getMarketingCosts());
                long calculatedMarketingCosts = costs.multiply(BigDecimal.valueOf(100)).longValue();
                slkjStoreCostMarketing.setMarketingCosts(calculatedMarketingCosts);
                slkjStoreCostMarketing.setMarketingInstructions(marketing.getMarketingInstructions());
                slkjStoreCostMarketing.setStoreId(storeId);
                slkjStoreCostMarketing.setDelFlag("0");
                slkjStoreCostMarketingMapper.insertSlkjStoreCostMarketing(slkjStoreCostMarketing);
                marketingCost += slkjStoreCostMarketing.getMarketingCosts();
            }
            if (!marketingCost.equals(marketingCosts)){
                throw new UtilException("营销成本合计与计算结果不一致");
            }
        }
        return  storeCostNum;
    }

    /**
     * 修改门店成本上报
     *
     * @param costDto 门店成本上报
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateSlkjStoreCost(StoreCostDto costDto)
    {
        Long venueRent = new BigDecimal(costDto.getVenueRent()).multiply(BigDecimal.valueOf(100)).longValue();
        Long procurement = new BigDecimal(costDto.getProcurement()).multiply(BigDecimal.valueOf(100)).longValue();
        Long equipmentMaintenance = new BigDecimal(costDto.getEquipmentMaintenance()).multiply(BigDecimal.valueOf(100)).longValue();
        Long personnelCosts = new BigDecimal(costDto.getPersonnelCosts()).multiply(BigDecimal.valueOf(100)).longValue();
        Long deplete = new BigDecimal(costDto.getDeplete()).multiply(BigDecimal.valueOf(100)).longValue();
        Long marketingCosts = new BigDecimal(costDto.getMarketingCost()).multiply(BigDecimal.valueOf(100)).longValue();
        Long num = venueRent + procurement + equipmentMaintenance + personnelCosts + deplete + marketingCosts;
        BigDecimal totalCost = new BigDecimal(costDto.getTotalCost());
        long calculatedNum = totalCost.multiply(BigDecimal.valueOf(100)).longValue();
        if (!num.equals(Long.valueOf(calculatedNum))) {
            throw new UtilException("成本合计与计算结果不一致");
        }
        //slkjStoreCostMarketingMapper.deleteByStoreId(costDto.getStoreId());
        SlkjStoreCostMarketing slkjStoreCostMarketing = new SlkjStoreCostMarketing();
        List<MarketingDto> marketingDtos = slkjStoreCostMarketingMapper.selectSlkjStoreCostMarketingLists(costDto.getStoreId());
        List<MarketingDto> marketingList = costDto.getMarketingList();
        Long marketingCost = 0L;
        for (MarketingDto marketingDto : marketingDtos) {
            slkjStoreCostMarketing.setId(marketingDto.getId());
            slkjStoreCostMarketing.setStoreId(marketingDto.getStoreId());
            slkjStoreCostMarketing.setMarketingCosts(Long.valueOf(marketingDto.getMarketingCosts()) * 100);
            slkjStoreCostMarketing.setDelFlag("1");
            slkjStoreCostMarketingMapper.updateSlkjStoreCostMarketing(slkjStoreCostMarketing);
        }
        if (marketingList != null) {
            marketingCost = 0L;
            for(MarketingDto  marketing : marketingList){
                //循环向子表插入数据
                BigDecimal costs = new BigDecimal(marketing.getMarketingCosts());
                long calculatedMarketingCosts = costs.multiply(BigDecimal.valueOf(100)).longValue();
                slkjStoreCostMarketing.setMarketingCosts(calculatedMarketingCosts);
                slkjStoreCostMarketing.setMarketingInstructions(marketing.getMarketingInstructions());
                slkjStoreCostMarketing.setStoreId(costDto.getStoreId());
                slkjStoreCostMarketing.setDelFlag("0");
                slkjStoreCostMarketingMapper.insertSlkjStoreCostMarketing(slkjStoreCostMarketing);
                marketingCost += slkjStoreCostMarketing.getMarketingCosts();
            }
            if (!marketingCost.equals(marketingCosts)){
                throw new UtilException("营销成本合计与计算结果不一致");
            }
        }
        String storeMonth = costDto.getStoreMonth();
        SlkjStoreCost slkjStoreCost = new SlkjStoreCost();
        slkjStoreCost.setStoreId(costDto.getStoreId());
        slkjStoreCost.setShopId(costDto.getShopId());
        slkjStoreCost.setShopName(costDto.getShopName());
        slkjStoreCost.setStoreMonth(storeMonth);
        slkjStoreCost.setVenueRent(venueRent);
        slkjStoreCost.setProcurement(procurement);
        slkjStoreCost.setPurchaseInstructions(costDto.getPurchaseInstructions());
        slkjStoreCost.setEquipmentMaintenance(equipmentMaintenance);
        slkjStoreCost.setMaintenanceInstructions(costDto.getMaintenanceInstructions());
        slkjStoreCost.setEmployees(costDto.getEmployees());
        slkjStoreCost.setPersonnelCosts(personnelCosts);
        slkjStoreCost.setDeplete(deplete);
        slkjStoreCost.setMarketingCost(marketingCosts);
        slkjStoreCost.setTotalCost(num);
        slkjStoreCost.setUpdateBy(SecurityUtils.getUsername());
        slkjStoreCost.setUpdateTime(DateUtils.getNowDate());
        return slkjStoreCostMapper.updateSlkjStoreCost(slkjStoreCost);
    }

    // /**
    //  * 批量删除门店成本上报
    //  *
    //  * @param storeIds 需要删除的门店成本上报主键
    //  * @return 结果
    //  */
    // @Override
    // public int deleteSlkjStoreCostByStoreIds(Long[] storeIds)
    // {
    //     return slkjStoreCostMapper.deleteSlkjStoreCostByStoreIds(storeIds);
    // }
    //
    // /**
    //  * 删除门店成本上报信息
    //  *
    //  * @param storeId 门店成本上报主键
    //  * @return 结果
    //  */
    // @Override
    // public int deleteSlkjStoreCostByStoreId(Long storeId)
    // {
    //     return slkjStoreCostMapper.deleteSlkjStoreCostByStoreId(storeId);
    // }
}
